package com.element.security.exception;

import com.common.core.exception.code.BaseErrorCode;
import com.common.core.exception.code.SecurityErrorCode;
import com.common.core.results.VoidResult;
import com.element.security.utils.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @auther zhangwj
 * @date 2021/3/18 下午5:11
 */
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {

    private final Logger logger = LoggerFactory.getLogger(AuthExceptionEntryPoint.class);

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
        Throwable cause = authException.getCause();
        if (cause instanceof InvalidTokenException) {
            logger.error("InvalidTokenException异常,请求路径:{},异常信息:", request.getServletPath(), cause);
            ResponseUtil.writeJson(response, VoidResult.failed(SecurityErrorCode.A_INVALID_TOKEN_EXCEPTION));
        } else if (cause instanceof OAuth2AccessDeniedException) {
            logger.error("OAuth2AccessDeniedException异常,请求路径:{},异常信息:", request.getServletPath(), cause);
            ResponseUtil.writeJson(response, VoidResult.failed(SecurityErrorCode.A_ACCESS_DENIED));
        } else if (cause instanceof GlobalAuthenticationException) {
            logger.error("GlobalAuthenticationException异常,请求路径:{},异常信息:", request.getServletPath(), cause);
            ResponseUtil.writeJson(response, VoidResult.failed(SecurityErrorCode.SYS_EXCEPTION_CODE.getErrNum(), cause.getMessage()));
        } else if (authException instanceof InsufficientAuthenticationException) {
            logger.error("InsufficientAuthenticationException异常,请求路径:{},异常信息:", request.getServletPath(), authException);
            ResponseUtil.writeJson(response, VoidResult.failed(SecurityErrorCode.A_INSUFFICIENT_AUTHENTICATION_ERROR));
        } else {
            logger.error("未知异常,请求路径:{},异常信息:", request.getServletPath(), authException);
            ResponseUtil.writeJson(response, VoidResult.failed(BaseErrorCode.SYS_EXCEPTION_CODE));
        }
    }
}
